<template>
  <view class="mine">
    <view class="top-container">
      <u-avatar
        :src="memberStore.profile?.photo"
        shape="square"
        size="52"
        @tap="onAvatarChange"
      ></u-avatar>
      <view class="info">
        <view v-if="memberStore.profile">
          <text class="username" @tap.stop="changeModalShow = true">{{
            memberStore.profile?.nickname
          }}</text>
          <text class="tel">{{
            memberStore.profile?.tel ? memberStore.profile?.tel : '未绑定手机（需实名登记）'
          }}</text>
        </view>
        <view v-else open-type="getUserInfo" @tap="loginOrRegister">
          <text class="operate">注册 / 登陆</text>
          <text class="remark">请登陆医疗小程序</text>
        </view>
      </view>
    </view>
    <view class="navigator-container">
      <u-grid :border="false" col="4" @click="navigatorHandle">
        <u-grid-item
          :name="`/user/fill_user_info/fill_user_info?type=${
            memberStore.profile?.tel === null || memberStore.profile?.tel === ''
              ? 'insert'
              : 'update'
          }`"
        >
          <view class="navigator-icon">
            <view class="navigator-icon-1" />
          </view>
          <text class="title">实名登记</text>
        </u-grid-item>
        <u-grid-item name="我的医生">
          <view class="navigator-icon">
            <view class="navigator-icon-2" />
          </view>
          <text class="title">我的医生</text>
        </u-grid-item>
        <u-grid-item name="检查报告">
          <view class="navigator-icon">
            <view class="navigator-icon-3" />
          </view>
          <text class="title">检查报告</text>
        </u-grid-item>
        <u-grid-item name="电子处方">
          <view class="navigator-icon">
            <view class="navigator-icon-4" />
          </view>
          <text class="title">电子处方</text>
        </u-grid-item>
      </u-grid>
    </view>
    <view class="publicity-container">
      <image :src="mineData.publicityBannerUrl" mode="widthFix" class="banner" />
    </view>
    <view class="mine-container">
      <view class="title-row">
        <text class="title">我的问诊</text>
        <u-icon label="更多" labelPos="left" size="15" name="arrow-right"></u-icon>
      </view>
      <view class="content">
        <u-grid :border="false" @click="navigatorHandle" col="5">
          <u-grid-item v-for="item in mineData.orderItems" :key="item.label" :name="item.url">
            <image :src="item.icon" mode="widthFix" class="navigator-icon"></image>
            <text class="title">{{ item.label }}</text>
          </u-grid-item>
        </u-grid>
        <image :src="mineData.otherBannerUrl" mode="widthFix" class="banner"></image>
      </view>
    </view>
    <view class="service-container">
      <view class="title-row">
        <text class="title">医疗服务</text>
        <u-icon label="更多" labelPos="left" size="15" name="arrow-right"></u-icon>
      </view>
      <view class="content">
        <u-grid :border="false" @click="navigatorHandle" col="5">
          <u-grid-item v-for="item in mineData.services" :key="item.label" :name="item.url">
            <image :src="item.imgUrl" mode="widthFix" class="navigator-icon"></image>
            <text class="title">{{ item.label }}</text>
          </u-grid-item>
        </u-grid>
      </view>
    </view>
    <view class="ad-container">
      <image :src="mineData.bannerList[1]" mode="widthFix" class="banner" />
    </view>
    <u-modal
      :show="changeModalShow"
      title="请输入您的昵称"
      ref="modal"
      :showCancelButton="true"
      @confirm="changeNickname"
      @cancel="changeModalShow = false"
    >
      <u-input
        v-model="nickname"
        clearable
        type="text"
        :maxlength="10"
        placeholder="请输入您的昵称"
      />
    </u-modal>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useMemberStore } from '@/stores'
import { mineConst } from './mineConst'
import { PostLoginByTel, postLoginWxMinAPI } from '@/services/login'
import { putMemberProfileApi, getMemberProfileApi } from '@/services/profile'
import type { LoginResult } from '@/types/member'
import { onShow } from '@dcloudio/uni-app'

const modal = ref()
const memberStore = useMemberStore()
const mineData = mineConst()
const changeModalShow = ref(false)

const navigatorHandle = (name: string) => {
  uni.navigateTo({
    url: name,
  })
}

//修改昵称
const nickname = ref('')
const changeNickname = async () => {
  if (nickname.value !== '') {
    const res = await putMemberProfileApi({ id: memberStore.profile!.id, nickname: nickname.value })
    memberStore.profile!.nickname = nickname.value
    changeModalShow.value = false
  } else {
    uni.showToast({
      title: '请输入昵称',
      icon: 'none',
    })
  }
}

//修改头像
const onAvatarChange = () => {
  // #ifdef MP-WEIXIN
  console.log(1)
  uni.chooseMedia({
    // 文件个数
    count: 1,
    // 文件类型
    mediaType: ['image'],
    success: (res) => {
      // 本地路径
      const { tempFilePath } = res.tempFiles[0]
      // 上传
      uploadFile(tempFilePath)
    },
  })
  // #endif
  // #ifdef WEB
  uni.chooseImage({
    count: 1,
    success: (res) => {
      // 本地路径
      const { tempFilePaths } = res
      // 上传
      uploadFile(tempFilePaths[0])
    },
  })
  // #endif
}

// 文件上传-兼容小程序端、H5端、App端
const uploadFile = (file: string) => {
  // 文件上传
  uni.uploadFile({
    url: '/user/uploadPhoto',
    name: 'file',
    filePath: file,
    header: {
      token: memberStore.profile!.token,
    },
    formData: {
      id: memberStore.profile!.id,
    },
    success: (res) => {
      if (res.statusCode === 200) {
        const photo = JSON.parse(res.data).result
        // 个人信息页数据更新
        // profile.value.avatar = avatar
        // Store头像更新
        memberStore.profile!.photo = photo
        uni.showToast({ icon: 'success', title: '更新成功' })
        reLaunchPage()
      } else {
        uni.showToast({ icon: 'error', title: '出现错误' })
      }
    },
  })
}

// 微信登录
const loginOrRegister = () => {
  // #ifdef MP-WEIXIN
  uni.login({
    provider: 'weixin',
    success: async (res) => {
      const { result, msg } = await postLoginWxMinAPI({ code: res.code })
      loginSuccess(result, msg)
    },
  })
  // #endif

  // #ifdef H5
  uni.showModal({
    title: '登录',
    editable: true,
    placeholderText: '请输入手机号',
    cancelText: '取消',
    confirmText: '登录',
    showCancel: true,
    success: (res) => {
      if (res.confirm) {
        if (uni.$u.test.mobile(res.content)) {
          PostLoginByTel({ tel: res.content! }).then((res) => {
            loginSuccess(res.result, res.msg)
          })
        }
      }
    },
  })

  // #endif
}

const loginSuccess = (profile: LoginResult, msg: string) => {
  // 保存会员信息
  const memberStore = useMemberStore()
  memberStore.setProfile(profile)
  // 成功提示
  uni.showToast({
    icon: 'success',
    title: msg,
  })
  reLaunchPage()
}

// 页面重新加载
const reLaunchPage = () => {
  setTimeout(() => {
    uni.reLaunch({
      url: '/pages/mine/mine',
    })
  }, 500)
}

onShow(() => {
  if (memberStore.profile?.token && memberStore.profile?.token !== '') {
    // 获取会员信息接口
    getMemberProfileApi().then((res) => {
      const profile = { ...res.result, token: memberStore.profile!.token }
      memberStore.setProfile(profile)
    })
  }
})
</script>

<style lang="less">
@import url(mine.less);
</style>
